package com.ushine.web.base.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ushine.web.base.BestRestTemplateTest;
import com.ushine.web.component.http.HttpResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import javax.annotation.Resource;

@Slf4j
@RunWith(SpringRunner.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest
@AutoConfigureMockMvc
@Component
class LoginUtils {

    private static final String baseUrl = "";

    @Resource
    private BestRestTemplateTest bestRestTemplateTest;

    @Test
    void loginAndGetToken() {
        // 用户的token
        String token = "";
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("username", "13659630049");
        //MDY4ODRlN2QwN2QzN2U5MTI1NjlhMjE5M2M0M2IzNmI=
        body.add("password", "MDY4ODRlN2QwN2QzN2U5MTI1NjlhMjE5M2M0M2IzNmI=");
        HttpResponseVO httpResultVO = bestRestTemplateTest.sendPostRequestByForm(baseUrl + "/login", null, body);
        Object data = httpResultVO.getData();
        JSONObject json = (JSONObject) JSON.toJSON(data);
        token = json.getString("token");
        // 任务执行完毕后打印"Done"
        log.info("登录测试完毕：*****************************************************");
    }


    /**
     * 功能描述:
     * 〈 获取用户的token 〉
     *
     * @param
     * @return : java.lang.String
     * @author : yls
     * @date : 2022/4/11 16:49
     * @throws Exception
     */
    public String getToken(String username) {
        // 用户的token
        String token = "";
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
//        body.add("username", "13659630049");
        body.add("username", username);
        //MDY4ODRlN2QwN2QzN2U5MTI1NjlhMjE5M2M0M2IzNmI=
        body.add("password", "MDY4ODRlN2QwN2QzN2U5MTI1NjlhMjE5M2M0M2IzNmI=");
        HttpResponseVO httpResultVO = bestRestTemplateTest.sendPostRequestByForm(baseUrl + "/login", null, body);
        Object data = httpResultVO.getData();
        JSONObject json = (JSONObject) JSON.toJSON(data);
        token = json.getString("token");
        return token;
    }
}
